package com.ys.controller.api.finance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliOtherPayment;
import com.ys.entity.finance.TcwWanliOtherPaymentItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.TcwWanliOtherPaymentEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.finance.TcwWanliOtherPaymentService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwWanliOtherPayment")
public class ApiInterTcwWanliOtherPaymentController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TcwWanliOtherPayment> commonApiService;
	@Autowired
	private CommonApiService<TcwWanliOtherPaymentItem> commonApiServiceDetail;
	@Autowired
	private TcwWanliOtherPaymentService tcwWanliOtherPaymentService;

	@Autowired
	private PdfService pdfService;
	
	@RequiresPermissions("tcwWanliOtherPayment:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwWanliOtherPaymentItem cond){
		
		cond = setSeachSql(cond);
		return commonApiServiceDetail.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcwWanliOtherPayment:add")
	public R add(String bid, String depositPlatformCode, Integer payType, String countryCode, String currencyCodeOut, BigDecimal exchangeRate, String premark, BigDecimal amountTotalLocal, BigDecimal amountTotalCny, String subData) {
		try {
			//修改
			return tcwWanliOtherPaymentService.add(bid, depositPlatformCode, payType, countryCode, currencyCodeOut, exchangeRate, premark, amountTotalLocal, amountTotalCny, subData, MenuId.TCW_WanliOtherPayment);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("tcwWanliOtherPayment:add")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(String bid, String depositPlatformCode, Integer payType, String countryCode, String currencyCodeOut, BigDecimal exchangeRate, String premark, BigDecimal amountTotalLocal, BigDecimal amountTotalCny, String subData){
		try {
			return tcwWanliOtherPaymentService.edit(bid, depositPlatformCode, payType, countryCode, currencyCodeOut, exchangeRate, premark, amountTotalLocal, amountTotalCny, subData, MenuId.TCW_WanliOtherPayment);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 批量修改费率
	 */
	@RequiresPermissions("tcwWanliOtherPayment:batchEditExchangeRate")
	@PostMapping("/batchEditExchangeRate")
    @ResponseBody
	public R batchEditExchangeRate(BigDecimal exchangeRate, String subData){
		try {
			return tcwWanliOtherPaymentService.batchEditExchangeRate(exchangeRate, subData);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 生成流水
	 */
	@RequiresPermissions("tcwWanliOtherPayment:generateRunning")
	@PostMapping("/generateRunning")
    @ResponseBody
	public R generateRunning(String bids){
		try {
			String[] bidArr = bids.split(",");
			for(String bid : bidArr) {
				tcwWanliOtherPaymentService.generateRunning(bid);
			}
			return R.ok("操作完成");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("tcwWanliOtherPayment:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setId(id).queryFirst();
		try {
    		String loginUserId = ShiroUtils.getUserId();
			return tcwWanliOtherPaymentService.flowPass(tcwWanliOtherPayment.getBid(), loginUserId);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliOtherPayment:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setId(id).queryFirst();
		try {
			return tcwWanliOtherPaymentService.flowRefuse(tcwWanliOtherPayment.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliOtherPayment:add")
	@PostMapping("/flowInit")
    @ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setId(id).queryFirst();
		try {
			return tcwWanliOtherPaymentService.flowInit(tcwWanliOtherPayment.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@RequiresPermissions("tcwWanliOtherPayment:add")
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tcwWanliOtherPaymentService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcwWanliOtherPayment:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliOtherPaymentItem cond) throws Exception{
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCW_WanliOtherPayment)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TcwWanliOtherPayment> util = new ExportExcelUtils<TcwWanliOtherPayment>(new TcwWanliOtherPayment());
        
        String toFilePath = util.exportExcel(listData, listField, "万里汇外币付款单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliOtherPaymentItem setSeachSql(TcwWanliOtherPaymentItem cond){
    	
    	cond.addLeftJoin("TCW_WanliOtherPayment B ON B.Bid = A.Pbid")
				.addField("B.CreateTime openTime")
	    		.addField("B.Bid bid")
	    		.addField("B.EffectStock effectStock")
	    		.addField("B.PayType payType")
	    		.addField("B.CurrencyCodeOut currencyCodeOut")
	    		.addField("B.ExchangeRate exchangeRate")
	    		.addField("B.Remark premark")
	    		.addField("ROUND(B.ExchangeRate * (A.Amount + A.Fee), 2) amountCny")
	    		.addField("B.AmountTotalLocal amountTotalLocal")
	    		.addField("B.AmountTotalCny amountTotalCny")
	    		.addField("B.StateRunning stateRunning")
    		.addLeftJoin("YS_ProcInst B99 ON B99.Bid = B.Bid")
	    		.addField("B99.UpdateTime auditTime")
	    		.addField("B99.CreateUserId createUserId")
    		.addLeftJoin("TS_UserInfo B100 ON B100.UserId = B99.CreateUserId")
	    		.addField("B100.UserId createUserId")
	    		.addField("B100.UserName createUserName")
	    		.addField("B100.DeptId createUserDeptId");
    	
    	cond.addLeftJoin("THR_OperateCompanyApply B1 on B1.Vgsbm = A.Vgsbm")
			.addField("B1.Vgsjc vgsjc");
    	
    	cond.addLeftJoin("TCW_DepositPlatform C ON C.Code = B.DepositPlatformCode")
    		.addField("C.PlatformName platformName")
    		.addField("C.Code depositPlatformCode")
    		.addField("C.Name depositPlatformName")
    		.addField("C.Name depositPlatformName");
    	
    	cond.addLeftJoin("TB_CompanyInfo D on D.Vid = C.CompanyVid")
			.addField("D.Vid companyVid")
			.addField("D.Vname companyVname");
		
    	cond = commonApiServiceDetail.dataAuth(MenuId.TCW_WanliOtherPayment, cond);
		
        return  cond;
    }


	/**
	 * 打印
	 */
	@RequestMapping("/exportdy")
	@ResponseBody
	public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
		List<Map<String,Object>> infoList = new TcwWanliOtherPayment()
				.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
				.addField("U.DeptName AS deptName")//制单人部门
				.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间

				.addLeftJoin("TCW_DepositPlatform D on D.Code = A.DepositPlatformCode")
				.addField("D.Code depositPlatformCode")//账号编码
				.addField("D.Name depositPlatformName")//账号名称
				.addField("D.PlatformName platformName")//收款平台名称
				.addLeftJoin("TB_CompanyInfo tci ON tci.Vid = D.CompanyVid")
				.addField("tci.Vid companyVid")
				.addField("tci.Vname companyVname")

				.addLeftJoin("TCW_WanliOtherPaymentItem S on S.Pbid = A.Bid")
				.addField("S.Amount amount,S.vyhzhmc vyhzhmc,S.vyhzh vyhzh,S.vkhh vkhh")//付款金额

				.setBid(bid)
				.queryMap();

		if(infoList!=null && infoList.size()>0){
			Map<String,Object> sonByOne = infoList.get(0);

			BigDecimal sonAmountTotal = BigDecimal.ZERO;
			for (Map<String, Object> son : infoList){
				sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("amount").toString()));
			}

			String nameStr =  (sonByOne.get("vyhzhmc")!=null ? sonByOne.get("vyhzhmc").toString():"")
					+ "/" + (sonByOne.get("vyhzh")!=null ? sonByOne.get("vyhzh").toString():"")
					+ "/" + (sonByOne.get("vkhh")!=null ? sonByOne.get("vkhh").toString():"");

			List<NameValueDto> listData = new ArrayList<>();
			listData.add(new NameValueDto("单据编号",bid));
			listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
			listData.add(new NameValueDto("收款账号",nameStr));
			listData.add(new NameValueDto("付款类型", TcwWanliOtherPaymentEnum.PayType.getName(Integer.parseInt(sonByOne.get("payType").toString()))));
			listData.add(new NameValueDto("付款金额",sonAmountTotal.toString() +" (" + sonByOne.get("currencyCodeOut").toString() + ")"));
			listData.add(new NameValueDto("付款说明",sonByOne.get("remark").toString()));
			String url = pdfService.generatePDF(bid,"万里汇外币付款单",(sonByOne.get("companyVname")!=null ? sonByOne.get("companyVname").toString():""), sonByOne.get("createTimeByStr").toString(),listData);
			return R.ok(url);
		}else {
			return R.error("未查询到要导出的数据");
		}


	}

}
